$(function() {

    //获取擅长领域的数据
    $.get(user_lawyer_url, function(data){
          
        }, "json").error(function(data) {
          var status_code = $.parseJSON(data.responseText);
          layer.msg(status_code.message);
        }).success(function(data) {
           var obj = data.data;
            var work_scope = obj;
            var options = '';
            $.each(work_scope, function(key, item) {
                options+='<option value="'+item.key+'">'+item.value+'</option>';
            });
            $("#work_scope").append(options);
        });

 //  //对律师的评价

 $.get(lawyer_evaluation_url, function(data){
          
      }, "json").error(function(data) {
        var status_code = $.parseJSON(data.responseText);
        layer.msg(status_code.message);
      }).success(function(data) {
         var questions = data.data;
          $.each(questions, function(key, item) {
              var str = "";
              var contact = "";

              if (!item.user_id) {
                 contact = "匿名";
              } else if (item.user_phone) {
                  contact = item.user_phone;
                  contact = contact.substring(0, 3) + '********';
              } else if (item.user_email) {
                  contact = item.user_email;
                  contact = contact.substring(0, 3) + '********';
              }

              //案源推送 循环数据不能写在 jQuery(".caseSourcePush").slide({调用的下面
              str +='<li><p><label class="name" style=" width:50px">' + item.creator_realname + '</label><label class="date">'+item.evaluate_created_at+'</label><label class="serviceEvaluation" data-score="'+item.evaluate_score+'"></label></p><p class="evaluationContent">'+item.evaluate_comment+'</p></li>';
              $(".lawyerEvaluation .infoList").append(str);
          
          });

          jQuery(".lawyerEvaluation").slide({
            mainCell:".bd ul",
            autoPlay:true,
            effect:"topMarquee", //效果
            vis:8, //可视个数
            interTime:50 //运行速度
          });


  //显示心的个数
  $('.serviceEvaluation').raty({ readOnly: true, score: function() {
    return $(this).attr('data-score');
  } });

});

  //上传图片的插件
  //初始化jQuery的文件上传控件
  $('#avatar_file').fileupload({
      limitMultiFileUploads : 1,
      limitMultiFileUploadSize : 1,
      limitMultiFileUploadSizeOverhead : 512,
      limitConcurrentUploads : 1,
        sequentialUploads : true,
      headers: 
        {"Accept":"application/json"}, //必须有
          dataType: "json", //表示返回值类型，不必须
      formData:{
        _token:token
      },
      messages: {uploadedBytes: 'Uploaded bytes exceed file size'},

      done: function (e, data) {//设置文件上传完毕事件的回调函数 
          var obj = data.result;
          var avatar = obj.data.file_path;
          var file_name = obj.data.file_name;
          if (file_name.length < 16) {
            file_name = file_name
          }else{
            file_name = file_name.substring(0,16)+'...'
          }
          var fileExt=( /[^.]+$/.exec(avatar.toUpperCase())); 
          var type = fileExt[0];
          $(".btn-success").append('<input type="hidden" name="file_paths[]" value="'+avatar+'"><input type="hidden" name="file_names[]" value="'+file_name+'">');
          layer.msg("上传文件成功！");
            $(".filename ul").append('<li>'+file_name+'&nbsp;&nbsp;<a class="delet" href="javascript:void(0);" title="删除" style="color:#004799">  删除</a></li>');//文件名
            $(".avatar_js_cover").show();
             // var fileLen = $("input:hidden[name='file_paths[]']").length;
             var fileLen = $(".filename ul li").length;
             var nameLen = $("input:hidden[name='file_names[]']").length;
             if(fileLen>=2){
                 $('#avatar_file').attr("disabled",true);
             }
          
          
        },
        fail: function(e, data) {
            //错误提示
            /*console.info(data)*/
        }
    });

  //删除上传的文件
  $(document).on( "click", ".delet", function(e) {
   $this = $(this).parent();
   $this.hide();
   index = $this.index();
   $(this).parent().remove();
   $("input:hidden[name='file_paths[]']").eq(index).remove();
   $("input:hidden[name='file_names[]']").eq(index).remove();
   // var fileLen = $("input:hidden[name='file_paths[]']").length;
   var fileLen = $(".filename ul li").length;
   var nameLen = $("input:hidden[name='file_names[]']").length;
   if(fileLen<2){
     $('#avatar_file').attr("disabled",false);
   }
    stopDefault(e);
  })



var url = attrUrl+"/lawyer/list_lawyers?rows_per_page=12";
getcontimg(url);
var getcontimgArr = "";
function getcontimg(url){
    $(".contQues-img").empty();
    var loading = '<dl><div class="loading">加载中...</div></dl>'; 
    $(".contQues-img").append(loading);
    $.get(url,function(data){

    }, "json").error(function(data) {
        // layer.msg("请求失败！")
        var status_code = $.parseJSON(data.responseText);
        layer.msg(status_code.message);
    }).success(function(data) {
      $(".loading").parent().remove();
      var obj = data.data;
      getcontimgArr = obj;
      if(obj.length > 1){
        for(var i=0;i<obj.length;i++){
            var str ='<li><a href="'+attrUrl+'/lawyer/'+obj[i].id+'" rel="nofollow"><img src="'+obj[i].avatar+'" alt=""></a></li>';
            $(".contQues-img").append(str);
            $(".contQuesContxt").show();
            if(i == 0){
                  $(".lawyerPortrait").attr("src",obj[i].avatar);
                  $(".thisInfo .name").text(obj[i].realname);
                  $(".thisInfo .practitioners").text(obj[i].practice_period);

                  var work_scope = obj[i].work_scope;
                  var options = '';
                  $.each(work_scope, function(key, item) {
                      options+='<label value="'+item.key+'">'+item.value+'</label> &nbsp;&nbsp;';
                  });
                  $(".thisInfo .pracScope").append(options);

                  var introduce = obj[i].introduce;
                  if(introduce != null){
                    if(introduce.length > 120){
                      introduce = introduce.substr(0,120)+'......';
                    }else{
                      introduce = introduce;
                    }
                  }else{
                    introduce = "";
                  }
                  $(".personalProfile").text(introduce);
            }
        }
      }else{
        var str ='<li>暂无数据</li>';
        $(".contQuesContxt").hide();
        $(".contQues-img").append(str);
      }

    });
}

  //不想等待直接联系律师  /*is_recommended=1*/
  $(document).on( "mouseover", ".contQues-img li", function(e) { 
      var list = getcontimgArr;
      var index = $(this).index();
      $(".lawyerPortrait").attr("src","");
      $(".thisInfo .name").text("");
      $(".thisInfo .practitioners").text("");
      $(".thisInfo .pracScope").text("");
      $(".personalProfile").text("");
        for(var i=0;i<list.length;i++){
          if(i == index){
                $(".lawyerPortrait").attr("src",list[i].avatar);
                $(".thisInfo .name").text(list[i].realname);
                $(".thisInfo .practitioners").text(list[i].practice_period);
                var work_scope = list[i].work_scope;
                var options = '';
                $.each(work_scope, function(key, item) {
                    options+='<label value="'+item.key+'">'+item.value+'</label> &nbsp;&nbsp;';
                });
                $(".thisInfo .pracScope").append(options);
                var introduce = list[i].introduce;
                if(introduce != null){
                  if(introduce.length > 120){
                    introduce = introduce.substr(0,120)+'......';
                  }else{
                    introduce = introduce;
                  }
                }else{
                  introduce = "";
                }
                $(".personalProfile").text(introduce);
          }
        }

      stopDefault(e);
  })
  
    //最活跃的律师
    var active_url = attrUrl+"/lawyer/list_lawyers?order_by=active&rows_per_page=5";
    var loading = '<li><div class="loading">加载中...</div><br/></li>'; 
    $(".rightlv ul").append(loading);
    $.get(active_url, function(data){        
        }, "json").error(function(data) {
          var status_code = $.parseJSON(data.responseText);
          layer.msg(status_code.message);
        }).success(function(data) {
          $(".loading").parent().remove();
          var obj = data.data;
          var work_scope = obj;
             for(var i=0; i<obj.length;i++){
                var options = '';
                $.each(work_scope, function(key, item) {
                  options+='<li>'
                    options+='<a href="'+attrUrl+'/lawyer/'+item.id+'"><img class="lvimg" src="'+item.avatar+'"></a>'
                    options+='<div class="lvtextbox">'
                      options+='<p><a href="'+attrUrl+'/lawyer/'+item.id+'"  class="lvname">'+item.realname+'</a>&nbsp;<span style="color:#666">律师</span></p>'
                      options+='<p><span>'+item.practice_period+'</span> <span>'+item.province+'</span></p>'
                      options+='<p>'
                          for (var i=0; i<item.average_evaluate_score; i++) {
                          options+='<img src="'+attrUrl+'/img/star-on.png">'
                          }
                          for (var i=0; i<5-item.average_evaluate_score; i++) {
                          options+='<img src="'+attrUrl+'/img/star-off.png">'
                          }
                       options+='</p>'
                      options+='<p>评价&nbsp;'+item.average_evaluate_score+'&nbsp;案例&nbsp;'+item.free_reply_count+'</p>'
                    options+='</div>'
                  options+='</li>';
                });
              };
                $(".rightlv ul").append(options);
        });
          

  //提交咨询
  $(document).on( "click", ".subAdvisory", function(e) { 
      var title = $.trim($("#title").val());
      var content = $.trim($("#content").val());
      var work_scope = $.trim($("#work_scope").val());
      var layerWeiXinCode = '<div class="weixincode">'
                layerWeiXinCode+='<h3 class="distance">提交成功！感谢您的咨询，律团网的律师会尽快为您解答！</h3>'
                  layerWeiXinCode+='<h3 class="distance">亲，要注册或者登录以后才能看到律师对您的回答哦。</h3>'
                  layerWeiXinCode+='<a href="'+register+'" class="jiushizhege"><span style="color:#FFF">去注册</span></a>'
                  layerWeiXinCode+='<a href="'+login+'" class="jiushizhege"><span style="color:#FFF">去登陆</span></a>'
          layerWeiXinCode+='</div>';
      var WeiXinImg = '<div class="weixincode"><br><br>'
            WeiXinImg+='<p>提交成功！感谢您的咨询，律团网的律师会尽快为您解答！</p><br>'
            WeiXinImg+='<p class="WeiXinImg"></p>'
            WeiXinImg+='<br><p><p>扫一扫<span style="color:#ff446f">关注服务号，随时随地收到回复</span></p>'
          WeiXinImg+='</div>'
      if(work_scope.length < 1){
          layer.msg('请选择案件类型！', {time: 2000});
          return false;
      }else if(title.length<1){
          layer.msg('标题不能为空！', {time: 2000});
          return false;
      }else if(content.length < 1){
          layer.msg('内容不能为空！', {time: 2000});
          return false;
      }else if(content.length < 20){
          layer.msg('内容字数不能小于20字！', {time: 2000});
          return false;
      }else{

          var loading = layer.msg('加载中...', {icon: 16});
          var inquery = $("#inquery_create_form");
          $(this).attr("disabled","disabled");
          $.post(attrUrl+"/center/question/insert/question", inquery.serialize(),
             function(data){
                $(':input',inquery).not(':button, :submit, :reset, :hidden').val(''); 
                if(islogin == "" || islogin == null){
                    var weixincode = layer.open({
                          type: 1, //基本层类型  可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）。 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
                          title: false, //标题
                          closeBtn: true,  //关闭按钮
                          shade:0.3,  //遮罩默认是0.3透明度
                          shadeClose: false,  //是否点击遮罩关闭
                          area: ['450px', '400px'],
                          skin: 'yourclass', //样式类名
                          content: layerWeiXinCode //内容
                    });
                }else{
                    // layer.msg("提交成功！感谢您的咨询，律团网的律师会尽快为您解答！");
                    var weixincode = layer.open({
                          type: 1, //基本层类型  可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）。 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
                          title: false, //标题
                          closeBtn: true,  //关闭按钮
                          shade:0.3,  //遮罩默认是0.3透明度
                          shadeClose: false,  //是否点击遮罩关闭
                          area: ['450px', '360px'],
                          skin: 'yourclass', //样式类名
                          content: WeiXinImg //内容
                    });
                    $(".filename ul li").remove();
                    $("input:hidden[name='file_paths[]']").remove();
                    $("input:hidden[name='file_names[]']").remove();
                }
                layer.close(loading); 
                 $(".subAdvisory").removeAttr('disabled'); 
                 // var url = attrUrl+"/lawyer/list_lawyers?rows_per_page=12&q="+work_scope;
                 // getcontimg(url); 
                 
             }, "json").error(function(data) {
               var obj = $.parseJSON(data.responseText);
               /*if(obj.error_messages.title.length > 0){
                alert(obj.error_messages.title);
               }
               if(obj.error_messages.content.length > 0){
                alert(obj.error_messages.content);
               }*/
             });
             
             return true;
      }
      stopDefault(e);
  });

  // 加载更多
  
  $(document).on("click",".loadMore",function(e){
    index++
    var keyword = $("#keyword").val();
      if (keyword != null && keyword.length != 0) {
        params ='&q='+keyword;
      }else{
        params =''
      }
    getAllUrl(params);
  })
// 点击搜索
  $(document).on("click","#subSearch",function(e){
      var keyword = $("#keyword").val();
      $(".js-appendContxt").empty();
      if (keyword != null && keyword.length != 0) {
        params ='&q='+keyword;
      }else{
        params =''
      }
      // window.location.href="{{ Config::get('app.url') }}/question/create?"+params;
      getAllUrl(params);
    });

  // enter按键搜索
  var j = 0;
    document.onkeydown = function(e) {
        var keyword = $("#keyword").val();
        var params ='q='+keyword;
        var e = event || window.event || arguments.callee.caller.arguments[0],
         keycode = e.which || e.keyCode;
         if (keycode==13) {
            if (keyword != null && keyword.length != 0) {
            j++;
                if(!j==0){
                  var keyword = $("#keyword").val();
                  $(".js-appendContxt").empty();
                  if (keyword != null && keyword.length != 0) {
                    params ='&q='+keyword;
                  }else{
                    params =''
                  }
                  getAllUrl(params);
                }
            } 
            return false; 
         }else{
            return true;
         }
         stopDefault(e);
    }
  // 精品回答
  var index = 1
  var params =''
  getAllUrl(params);
  function getAllUrl(params){
    var loading = '<dl><div class="loading" style="margin-top:10px;">加载中...</div></dl>';
    $(".js-appendContxt").append(loading);
    // console.info('url',url)
    $.get(attrUrl+'/question/list_questions?rows_per_page=8&page='+index+params,function(data){
      }, "json").error(function(data) {
        layer.msg("请求失败！")
      }).success(function(data) {
        $(".loading").parent().remove();
        var obj = data.data;
        console.info(obj)
        currentLength = obj.length;
        var str =''
        if(currentLength < 8) {
            $(".loadMore").css("display","none");
          }else{
            $(".loadMore").css("display","");
          }
        for(var i=0;i<obj.length;i++){
          var lawyerName = ""
          if(obj[i].lawyer != null){
              lawyerName = obj[i].lawyer.realname;
          } 
          
            str+='<div class="otherQuercontxt">'
              str+='<div class="issue">'
               str+='<p><a class="textcontent" href="'+attrUrl+'/question/'+obj[i].id+'">'+obj[i].title+'</a><span style="float: right;color:#999;">'+obj[i].post_category+'</span></p>'
               str+='<p style="line-height:8px;">&nbsp;</p>'
               str+='<p><span style="color:#999;">'+lawyerName+' 律师</span><span class="time">'+obj[i].created_at+'</span></p>'
              str+='</div>'
            str+='</div>';
        }
        $(".js-appendContxt").append(str);
        
      });
  }


});

